<template>
  <div class="edit-page">
    <!-- 顶部标题 -->
    <Header />
    <div class="back-page">
      <!-- 页面内容 -->
      <div class="content">
        <!-- 标题 -->
        <div class="breadcrumb">
          <el-link type="primary" @click="navTo(`/companyInfo?id=${id}`)" icon="DArrowLeft">返回</el-link>
          <span>首页 / 我的控制台 / 修改企业信息</span>
        </div>
        <h2>修改企业信息</h2>

        <!-- 表单 -->
        <el-form :model="formData" :rules="rules" ref="formRef" label-width="170px" class="form gradient-box">
          <el-form-item label="单位名称" prop="enterprise">
            <el-input v-model="formData.enterprise"></el-input>
          </el-form-item>

          <el-form-item label="法定身份识别码" prop="creditCode">
            <el-input v-model="formData.creditCode"></el-input>
          </el-form-item>
          <el-form-item label="供应商经营资质证书类型" prop="certType">
            <el-select v-model="formData.certType" placeholder="请选择资质证书类型">
              <el-option
                v-for="option in supplierCertOptions"
                :key="option.dictValue"
                :label="option.dictLabel"
                :value="option.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="法定身份识别文件" prop="businessLicense">
            <UploadItem
              :action="`${config.baseUrl}/common/upload`"
              :fileList="formData.businessLicense"
              fileKey="businessLicense"
              @onSuccess="handleUploadSuccess"
              @onRemove="handleRemove"
              @onPreview="handlePreview"
              :limit="1"
            />
          </el-form-item>
          <el-form-item label="有效期" prop="periodOfValidity">
            <div style="display: flex; align-items: center">
              <el-date-picker
                v-model="formData.periodOfValidity"
                type="date"
                placeholder="请选择有效期"
                :disabled="formData.isLongTime == 1"
                style="flex: 1; margin-right: 10px"
              />
              <el-checkbox v-model="formData.isLongTime" :true-label="1" :false-label="0" @change="handleLongTimeChange">
                长期
              </el-checkbox>
            </div>
          </el-form-item>

          <el-form-item label="单位性质" prop="unitProperty">
            <el-select v-model="formData.unitProperty" placeholder="请选择单位性质">
              <el-option
                v-for="option in unitPropertyOptions"
                :key="option.dictValue"
                :label="option.dictLabel"
                :value="option.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="行业类别" prop="industryType">
            <el-checkbox-group v-model="formData.industryType">
              <el-checkbox
                v-for="option in supplierIndustryOptions"
                :key="option.dictValue"
                :label="option.dictLabel"
                :value="option.dictValue"
              />
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="住所" prop="address">
            <el-input v-model="formData.address"></el-input>
          </el-form-item>
          <el-form-item label="法定代表人/负责人" prop="legalRepresentative">
            <el-input v-model="formData.legalRepresentative"></el-input>
          </el-form-item>
          <el-form-item label="是否独立法人" prop="independentLegalEntity">
            <el-radio-group v-model="formData.independentLegalEntity">
              <el-radio value="1" size="large">是</el-radio>
              <el-radio value="0" size="large">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="单位类型" prop="unitType">
            <el-select v-model="formData.unitType" placeholder="请选择单位类型">
              <el-option v-for="option in unitTypeOptions" :key="option.dictValue" :label="option.dictLabel" :value="option.dictValue" />
            </el-select>
          </el-form-item>

          <el-form-item label="单位电子邮箱" prop="email">
            <el-input v-model="formData.email"></el-input>
          </el-form-item>

          <el-form-item label="供货商主要联系人" prop="name">
            <el-input v-model="formData.name"></el-input>
          </el-form-item>

          <el-form-item label="供货商主要联系人电话" prop="phone">
            <el-input v-model="formData.phone"></el-input>
          </el-form-item>
          <el-form-item label="法人授权书" prop="authorization">
            <UploadItem
              :action="`${config.baseUrl}/common/upload`"
              :fileList="formData.authorization"
              fileKey="authorization"
              @onSuccess="handleUploadSuccess"
              @onRemove="handleRemove"
              @onPreview="handlePreview"
              :limit="1"
            />
          </el-form-item>

          <el-form-item label="资质等级附件" prop="certLevel">
            <UploadItem
              :action="`${config.baseUrl}/common/upload`"
              :fileList="formData.certLevel"
              fileKey="certLevel"
              @onSuccess="handleUploadSuccess"
              @onRemove="handleRemove"
              @onPreview="handlePreview"
              :limit="1"
            />
          </el-form-item>
          <el-form-item label="供应商编码" prop="code">
            <el-input disabled v-model="formData.code"></el-input>
          </el-form-item>
          <el-form-item label="最后一次审批时间" prop="updateTime">
            <el-input disabled v-model="formData.updateTime"></el-input>
          </el-form-item>

          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="onCancel">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useDataStore } from "@/store/index.js"; // 引入 Pinia Store
import { vendorInfo, editVendor } from "@/api/vendor";
import { showMessage } from "../../utils/common";
import config from "../../utils/config";
import Header from "../../components/Header.vue";

const dataStore = useDataStore(); // 使用 Pinia Store

const route = useRoute();
const router = useRouter();
const navTo = (path) => {
  router.push(path);
};
const id = computed(() => route.query.id);

// 从 Store 中获取字典数据
const unitTypeOptions = computed(() => dataStore.unit_type);
const supplierCertOptions = computed(() => dataStore.supplier_cert);
const supplierIndustryOptions = computed(() => dataStore.supplier_industry);
const unitPropertyOptions = computed(() => dataStore.unit_property);

// 表单数据
const formData = ref({});

// 表单校验规则
const rules = {
  certType: [{ required: true, message: "请选择资质证书类型", trigger: "change" }],
  businessLicense: [{ required: true, message: "请上传营业执照或资质证明证书", trigger: "change" }],
  authorization: [{ required: true, message: "请上传法人授权书", trigger: "change" }],
  certLevel: [{ required: true, message: "请上传资质等级附件", trigger: "change" }],
  creditCode: [{ required: true, message: "统一社会信用代码不能为空", trigger: "blur" }],
  enterprise: [{ required: true, message: "单位名称不能为空", trigger: "blur" }],
  periodOfValidity: [
    {
      required: true,
      message: "请选择有效期",
      trigger: "change",
      validator: (rule, value, callback) => {
        if (formData.value.isLongTime === 1) {
          callback(); // 长期选中时直接通过验证
        } else if (!value) {
          callback(new Error("请选择有效期")); // 长期未选中且未选择日期时触发验证错误
        } else {
          callback(); // 验证通过
        }
      },
    },
  ],
  industryType: [{ required: true, message: "请选择行业类别", trigger: "change" }],
  address: [{ required: true, message: "住所不能为空", trigger: "blur" }],
  legalRepresentative: [{ required: true, message: "法人代表人不能为空", trigger: "blur" }],
  name: [{ required: true, message: "主要联系人不能为空", trigger: "blur" }],
  phone: [
    { required: true, message: "联系人电话不能为空", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: ["blur", "change"] },
  ],
  email: [
    { required: true, message: "电子邮箱不能为空", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] },
  ],
  password: [
    { required: true, message: "密码不能为空", trigger: "blur" },
    {
      pattern: /^(?=.*[A-Za-z])(?=.*\d|(?=.*[!@#$%^&*])).{8,}$/,
      message: "密码至少包含大小写字母、数字或特殊字符的其中2种，长度不少于8位",
      trigger: "blur",
    },
  ],
  unitType: [{ required: true, message: "单位类型不能为空", trigger: "change" }],
  unitProperty: [{ required: true, message: "单位性质不能为空", trigger: "change" }],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.value.password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "验证码不能为空", trigger: "blur" }],
  agreement: [
    { required: true, message: "请勾选协议", trigger: "change" },

    {
      validator: (rule, value, callback) => {
        console.log(value, 112233);
        if (!value) {
          callback(new Error("请勾选协议"));
        } else {
          callback();
        }
      },
      trigger: "change",
    },
  ],
  independentLegalEntity: [{ required: true, message: "请选择是否为独立法人", trigger: "change" }],
};

const formRef = ref(null);
const handleUploadSuccess = (response, fileKey, fileName) => {
  console.log(response, fileKey);
  formData.value[fileKey] = response;
};
const handleLongTimeChange = () => {
  if (formData.value.isLongTime === 1) {
    formData.value.periodOfValidity = null; // 清空日期选择器的值
  }
};
const handlePreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
const handleRemove = (file, fileKey) => {
  console.log(file, fileKey);
  // 从业务逻辑中移除文件
  formData.value[fileKey] = [];
};
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log("提交成功", formData.value);

      // 将文件字段还原为字符串
      const serializeFileField = (field) => (Array.isArray(field) && field.length > 0 ? field.map((f) => f.url).join(",") : "");

      // 提交表单逻辑
      editVendor({
        ...formData.value,
        industryType: Array.isArray(formData.value.industryType) ? formData.value.industryType.join(",") : formData.value.industryType,
        businessLicense: serializeFileField(formData.value.businessLicense),
        authorization: serializeFileField(formData.value.authorization),
        certLevel: serializeFileField(formData.value.certLevel),
      }).then((res) => {
        if (res.code == 200) {
          showMessage("修改成功", "success");
          onCancel();
        }
      });
    } else {
      console.log("校验失败");
    }
  });
};

const onCancel = () => {
  router.push(`/companyInfo?id=${id.value}`);
};

//获取供应商基本信息
const getCompanyInfo = async () => {
  const res = await vendorInfo(id.value);
  if (res.code == 200) {
    const data = res.data;

    // 格式化文件字段
    const normalizeFileField = (field) =>
      typeof field === "string" && field ? [{ name: field.split("/").pop(), url: field }] : Array.isArray(field) ? field : [];

    data.businessLicense = normalizeFileField(data.businessLicense);
    data.authorization = normalizeFileField(data.authorization);
    data.certLevel = normalizeFileField(data.certLevel);
    data.industryType = data.industryType.split(",");
    // 删除 password 字段
    delete data.password;
    formData.value = data;
  }
};

onMounted(() => {
  getCompanyInfo();
});
</script>

<style scoped>
.back-page {
  min-height: calc(100vh - 56px);
  background: url("../../assets/f87147698f07020d4fea348f49da0166.png") no-repeat center center;
  background-size: cover;
}
.edit-page {
  font-family: Arial, sans-serif;
}

.header {
  display: flex;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ddd;
  background-color: #f5f5f5;
}

.header .logo {
  display: flex;
  align-items: center;
}

.header .logo span {
  margin-left: 16px;
  font-size: 18px;
  font-weight: bold;
}

.content {
  padding: 20px;
  width: 80%;
  margin: 0 auto;
}

.breadcrumb {
  color: #888;
  font-size: 14px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  span {
    margin-left: 10px;
  }
}

h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
}

.form {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
